package com.gitee.zhangchenyan.takin.common.utils;

import cn.hutool.core.convert.Convert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.AsyncContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Deacription TODO
 * @Author Administrator
 * @Date 2021/12/7 21:04
 * @Version 1.0
 **/
public class HttpServletUtils {

    public static void setCookie(String cookieKey, String cookieValue, int seconds) {
        Cookie cookie = new Cookie(cookieKey, cookieValue);
        cookie.setMaxAge(seconds);
        cookie.setPath("/");
        GetHttpServletResponse().addCookie(cookie);
    }

    public static void deleteCookie(String cookieKey) {
        Cookie cookie = new Cookie(cookieKey, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        GetHttpServletResponse().addCookie(cookie);
    }

    public static String getCookie(String token) {
        Cookie[] cookies = GetHttpServletRequest().getCookies();
        if (null == cookies) {
            return "";
        }
        for (Cookie item : cookies) {
            if (token.equals(item.getName())) {
                return item.getValue();
            }
        }
        return "";
    }

    public static String getSession(String token) {
        HttpSession session = GetHttpServletRequest().getSession();
        if (null == session) {
            return "";
        }
        return (String) session.getAttribute(token);
    }

    public static HttpServletRequest GetHttpServletRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    public static HttpServletResponse GetHttpServletResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }

}
